// @(#)db.cc
// Time-stamp: <2009-01-13 23:37:14 root>
// Copyright 2008 Julian Qian
// Author: root@localhost.localdomain
// Version: $Id: db.cc,v 0.0 2008/11/16 20:02:56 root Exp $
// Keywords: 

#include "db.hh"
#include "excep.hh"
#include "inifile.hh"


// Db* Db::_theDb = NULL;

// Db*
// Db::theDb(){
//     if(NULL == _theDb){
//         _theDb = new Db();
//     }
//     return _theDb;
// }

// void
// Db::endDb(){
//     delete _theDb;
// }

Db::Db(){
    Config* cnf = Config::theConfig(GEN_CONF_FILE);
    
    strncpy(username, cnf->read("DATABASE","USERNAME").c_str(), DB_CONF_LEN);
    strncpy(password, cnf->read("DATABASE","PASSWORD").c_str(), DB_CONF_LEN);
    strncpy(database, cnf->read("DATABASE","DATABASE").c_str(), DB_CONF_LEN);
    strncpy(hostname, cnf->read("DATABASE","HOSTNAME").c_str(), DB_CONF_LEN);

    conns_in_use_ = 0;    
}

Db::~Db(){
    mysqlpp::ConnectionPool::clear();
}

CONN*
Db::con(){
    /*
    if(_con->connected()){
        return _con;
    }else{
        _con = CONN(database, hostname, username, password);
    }
    */
    while (conns_in_use_ > CONN_USE_MAX) {
        // cout.put('R'); cout.flush(); // indicate waiting for release
        // TODO: ?? will hang Proto::auth() ??
        sleep(1);
    }

    ++conns_in_use_;
    return mysqlpp::ConnectionPool::grab();
}

void
Db::end(CONN* con){
    mysqlpp::ConnectionPool::release(con);
    --conns_in_use_;
}

CONN*
Db::create(){
    return new CONN(database, hostname, username, password);
}

void
Db::destroy(CONN* con){
    // Our superclass can't know how we created the Connection, so
    // it delegates destruction to us, to be safe.
    // cout.put('D'); cout.flush(); // indicate connection destruction
    delete con;
}

unsigned int
Db::max_idle_time()
{
    // Set our idle time at an example-friendly 3 seconds.  A real
    // pool would return some fraction of the server's connection
    // idle timeout instead.
    return 3;
}
